package com.example.recite_words.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.recite_words.MainActivity;
import com.example.recite_words.R;
import com.example.recite_words.util.Config;
import com.example.recite_words.util.Send_data;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import de.hdodenhof.circleimageview.CircleImageView;

public class Waiting extends MainActivity {
    private ProgressBar prog;
    private CircleImageView my_icon,your_icon;
    private FloatingActionButton back;
    private int isback = 0;
    private TextView waiting,myname,yourname;
    static Object wait_en = new Object();
    private static Object read_lock = new Object();
    public  static URI serverURI = URI.create(Config.BATTLE + "?myEmail="+MainActivity.TheUser.getId()+"&&name="+MainActivity.TheUser.getNickName());
    public static WebSocketClient client ;
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        Battle.round = 0;
        Battle.urScore = 0;
        Battle.myScore = 0;
        Battle.rightIndex = 0;
        Battle.en_finish = 0;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waitting);
        back = findViewById(R.id.wa_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isback = 1;

                Intent main_intent = new Intent(Waiting.this,Main.class);
                startActivity(main_intent);
                new Thread(() -> {
                    String data = "myEmail="+MainActivity.TheUser.getId();
                    Send_data.do_post(Waiting.this,data,Config.BATTLE_EXIT);
                    client.close();
                }).start();

            }
        });
        client = new WebSocketClient(serverURI) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
            }
            @Override
            public void onMessage(String message) {
                new Thread(() -> {
                    Message msg = Message.obtain();
                    msg.obj = message;
                    if (message.equals("add")) msg.what = 1;
                    else if (message.equals("done")) msg.what = 2;
                    else msg.what = 3;//说明匹配成功
                    Battle.handler.sendMessage(msg);
                }).start();
                // Log.e("JWebSocketClientService", "发送的消息：" + message);
            }
            @Override
            public void onClose(int code, String reason, boolean remote) {
            }

            @Override
            public void onError(Exception ex) {
            }

        };
        my_icon = findViewById(R.id.wa_my_icon);
        Uri uri = MainActivity.TheUser.IconToUri();
        if(uri != null){
            my_icon.setImageURI(uri);
        }
        else {
            my_icon.setImageResource(R.drawable.user_icon);
        }
        your_icon = findViewById(R.id.wa_your_icon);
        myname =findViewById(R.id.wa_myname);
        myname.setText(MainActivity.TheUser.getNickName());
        yourname = findViewById(R.id.wa_yourname);
        waiting =findViewById(R.id.wa_waiting);
        prog=findViewById(R.id.progressBar);
//        Drawable draw = this.getResources().getDrawable(R.drawable.grad);
//        draw.setBounds(prog.getProgressDrawable().getBounds());
//        prog.setProgressDrawable(draw);
//        prog.setProgress(0);
        start(prog);
        new Thread(() -> {
            match();}).start();
    }
    private void match(){
        if (!client.isOpen()){
        
            client.connect();
        }
        if(client.isClosed() || client.isClosing()){
            client.reconnect();
        }

        synchronized (wait_en) {
            try {
                wait_en.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(isback == 0) {
                waiting.post(new Runnable() {
                    @Override
                    public void run() {
                        waiting.setText("匹配成功");
                    }
                });
                new Thread(() -> {
                    synchronized (read_lock) {
                        String data = "Email=" + MainActivity.en_user.getId();
                        String FileType = Send_data.post_for_pic(data, Config.DOWNLOAD_FLIE, Waiting.this.getExternalFilesDir(null).getPath(), "en_icon");
                       // MainActivity.en_user.setIcon(Waiting.this.getExternalFilesDir(null).getPath() + "/en_icon." + FileType);
                        your_icon.post(new Runnable() {
                            @Override
                            public void run() {
                                Uri uri = MainActivity.en_user.IconToUri();
                                if (uri != null) {
                                    your_icon.setImageURI(uri);
                                } else {
                                    your_icon.setImageResource(R.drawable.user_icon);
                                }
                            }
                        });
                        yourname.post(new Runnable() {
                            @Override
                            public void run() {
                                yourname.setText(MainActivity.en_user.getNickName());
                            }
                        });
                        read_lock.notify();
                    }
                }).start();
                synchronized (read_lock) {
                    try {
                        read_lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent battle_intent = new Intent(Waiting.this, Battle.class);
                    startActivity(battle_intent);
                }
            }
        }
    }
    // 进度条开始变化的方法
    public void start(final ProgressBar progressBar) {
        // 耗时任务放在子线程种进行
        new Thread() {
            private int nowProgress;
            private int maxProgress;

            public void run() {
                // 得到进度条当前的值
                nowProgress = progressBar.getProgress();
                // 得到进度条最大值
                maxProgress = progressBar.getMax();
                // 当当前进度小于最大进度值时
                while (nowProgress < maxProgress) {
                    nowProgress++;
                    progressBar.setProgress(nowProgress);
                    // 表示在UI线程种更新TextView因为子线程不能更新UI

                    try {
                        // 延时模拟加载进度
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
        }.start();
    }
}
